<template>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="primary" @click="isEditable = !isEditable">
        {{ isEditable ? '锁定' : '编辑' }}
    </el-button>
    <!--<el-dialog v-model="dialogFormVisible" v-if="dialogFormVisible" title="添加资产类型" width="58%"> -->
    <!--   <Add :departmentdata="departmentdata" :assetForm="assetForm" @addSubmit="handleSubmit"></Add> -->
    <!-- </el-dialog>-->
    <el-button type="text" :disabled="!isEditable" @click="addType" >
        <el-icon><Plus /></el-icon>
        添加知识库类型
    </el-button>
    </div>  
    <el-table
        :data="typeData"
        style="width: 100%"
        row-key="id"
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
        <el-table-column prop="typeName" label="分类名称" />
        <el-table-column prop="typeCode" label="分类编码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
            <el-button
            type="primary"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="openEditDialog(scope.row)"
            title="编辑分类"
            >编辑</el-button>
            <el-button
            type="danger"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="removeType(scope.row.id)"
            title="删除该分类"
            >删除</el-button>
        </template>
        </el-table-column>
  </el-table>
    <el-dialog v-model="dialogFormVisible" title="新增资产分类" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="分类编码" prop="typeCode">
          <el-input v-model="form.typeCode" placeholder="请输入分类编码" />
        </el-form-item>

        <el-form-item label="分类描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入分类描述" />
        </el-form-item>

        <el-form-item label="父分类" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="rootType"
            :props="{ label: 'typeName', value: 'id', children: 'children' }"
            clearable
            placeholder="请选择父分类（可不选）"
          />
        </el-form-item>
        
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog
    v-model="dialogEditVisible"
    :title="修改资产分类"
    width="500px"
    >
    <el-form :model="form" label-width="80px">
        <el-form-item label="分类名称">
        <el-input v-model="form.typeName" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="rootCategories"
            :props="{ label: 'typeName', value: 'id', children: 'children' }"
            clearable
            placeholder="请选择父分类（可不选）"
          />
        </el-form-item>
        <el-form-item label="分类编码">
        <el-input v-model="form.typeCode" />
        </el-form-item>
        <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" />
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="dialogEditVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUpdateType">保存</el-button>
    </template>
    </el-dialog>
</template>
<script setup>

import {toRefs,onBeforeMount,onMounted,reactive,ref,computed} from "vue"
import { ElMessage,ElForm, ElFormItem, ElInput, ElButton,ElMessageBox } from 'element-plus';
import { Plus,Minus } from '@element-plus/icons-vue'
import { getKnowledgeTypeInfoHandler,delKnowledgeTypeInfoHandler,addKnowledgeTypeInfoHandler,updateKnowledgeTypeInfoHandler } from "../../api/knowledge.js"
import { base64Decode } from "../../utils/base64.js"
const data = reactive({
    typeData: [{ "parentId": "", "typeName": "", "typeCode": "","description": ""}]
})
const isEditable = ref(false)
const dialogFormVisible = ref(false)
const dialogEditVisible = ref(false)
const {typeData} = toRefs(data)
const formRef = ref(null)

const form = ref({
  id: null,
  parentId: null,
  typeName: '',
  typeCode: '',
  description: '',
  
})
// 过滤出主类型，避免选择子类型方法
function getRootType(treeData) {
  return treeData
    .filter(item => Number(item.parentId) === 0)
    .map(item => {
      return {
        ...item,
        children: [] // 清空子节点，只显示一级
      }
    })
}
// const rootCategories = computed(() => {
  // return categoryData.value.filter(item => item.parentId === 0)
//  return categoryData.value.filter(item => Number(item.parentId) === 0)
// })
const rootType = computed(() => getRootType(typeData.value))
const loadConfig = async()=>{
    try {
        const response = await getKnowledgeTypeInfoHandler()
        if (response.data.data) {
            // typeData.value = base64Decode(response.data.data.queryData)
            typeData.value =response.data.data.queryData
            console.log("categoryData==========20250813",typeData.value)
        }
    }
    catch(error){
        console.error("保存配置失败:", err)
        ElMessage({
                    message: error?.response?.data?.message || "查询失败，请重试",
                    type: 'error',
        })
    }
}
const addType=()=>{
    form.value = { parentId: null,typeName: '', typeCode: '', description: '' }
    dialogFormVisible.value=true
}
const submitForm = async() => {
    try{
        const valid = await formRef.value.validate()
        if(valid){
            console.log('新增分类数据:', form.value)
            const res = await addKnowledgeTypeInfoHandler(form.value)
            if (res.data) {
                console.log("res.data====20250821",res.data)
                ElMessage({
                message: res.data.message,
                type: 'success'})
            }
            dialogFormVisible.value = false
            await loadConfig()
        }
    } catch(error){
        console.error("添加失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "添加失败，请重试",
                    type: 'error',
        })
    }
  
}
const removeType=async(id)=>{
    try {
        console.log("id=======20250813",id)
        const intId = Number(id)
        const response = await delKnowledgeTypeInfoHandler(intId)
        
        if (response.data) {
            ElMessage({
                    message: response.data.message,
                    type: 'success',
            })
            console.log("delcategoryData==========20250821",response.data)
            await loadConfig()
            
        }
    } catch(error) {
        console.error("删除失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "删除失败，请重试",
                    type: 'error',
        })
        // throw err // 如果需要让调用方知道错误
    }
    
}
const openEditDialog=(row)=>{
    console.log("row======20250813",row)
    form.value={...row}
    dialogEditVisible.value = true
}
const saveUpdateType=async()=>{
    try {
        const id=form.value.id
        console.log("==============20250822",id)

        const res = await updateKnowledgeTypeInfoHandler(id,form.value)
        if (res.data){
            ElMessage({
                    message: res.data.message,
                    type: 'success',
            })
            console.log("updatetypeData==========20250822",res.data)
            dialogEditVisible.value = false
            await loadConfig()
        }
    }catch(error){
        console.error("更新失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "更新失败，请重试",
                    type: 'error',
        })
    }
}
onMounted(()=>{
  loadConfig()
})
</script>